package com.example.holle;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        EditText user= findViewById(R.id.user);
        EditText password = findViewById(R.id.password);
        TextView textView=findViewById(R.id.text);
        Button subButton =findViewById(R.id.sub);
        Button reButton=findViewById(R.id.re);
        subButton.setOnClickListener(view -> {
            Toast.makeText(this,"登录成功",Toast.LENGTH_SHORT).show();
            String data="data.txt";
            SharedPreferences sharedPreferences=null;
            SharedPreferences.Editor editor=null;
            try {
                sharedPreferences=getSharedPreferences(data,MODE_PRIVATE);
                editor=sharedPreferences.edit();
                editor.putString(user.getText().toString(),password.getText().toString());
                editor.commit();
            } catch (Exception e) {
                Toast.makeText(this,"保存失败:"+e.getStackTrace(),Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
            Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();

            try {
                sharedPreferences=getSharedPreferences(data,MODE_PRIVATE);
                textView.setText(user.getText()+":"+sharedPreferences.getString(user.getText().toString(),""));
            } catch (Exception e) {
                Toast.makeText(this,"读取失败",Toast.LENGTH_SHORT).show();
                throw new RuntimeException(e);
            }

        });
        reButton.setOnClickListener(view -> {
            textView.setText(null);
            user.setText(null);
            password.setText(null);
            String data="data.txt";
            SharedPreferences sharedPreferences=null;
            SharedPreferences.Editor editor=null;
            try {
                sharedPreferences=getSharedPreferences(data,MODE_PRIVATE);
                editor=sharedPreferences.edit();
                editor.remove(user.getText().toString());
                editor.commit();
            } catch (Exception e) {
                Toast.makeText(this,"删除失败:"+e.getStackTrace(),Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
            Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        });

    }

}